package com.study.Link;

public class LinkStore {

    Node headNode;

    public LinkStore() {
        headNode = new Node();
    }

    public void addElement(Object o) {
        Node node = new Node();
        node.element = o;
        if (this.headNode.next == null) {
            this.headNode.next = node;
            return;
        }
        Node temp = this.headNode.next;
        while (true) {
            if (temp.next == null) {
                temp.next = node;
                break;
            } else {
                temp = temp.next;
            }
        }
    }

    // 链表反转
    public void reverseKLink(LinkStore linkStore) {

        if (linkStore.headNode.next == null || linkStore.headNode.next.next == null) {
            System.out.println("link is null or only have one element ");
            return;
        }
        Node newHead = new Node();
        Node current = linkStore.headNode.next;
        Node temp = null;
        while (current != null) {
            temp = current.next;
            linkStore.headNode.next = current.next;
            current.next = newHead.next;
            newHead.next = current;
            current = temp;
        }
        linkStore.headNode.next = newHead.next;

    }
    // 删除单项链表元素
    public void delete(Node node){
        Node current = this.headNode.next;
        if (current == null){
            System.out.println("this linkStore is null");
        }

        Node temp = this.headNode;
        while (current!=null){
            if(current.element ==node.element){
                temp.next = current.next;
                break;
            }
            temp =temp.next;
            current= current.next;
        }

    }


    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("");
        if (this.headNode.next == null) {
            return "LinkStore is  null";
        }
        Node temp = headNode.next;
        while (true) {
            stringBuilder.append(temp.element);
            if (temp.next == null) {
                return stringBuilder.toString();
            }
            temp = temp.next;
        }
    }
}

class Node<T> {
    T element;
    Node next;

    @Override
    public String toString() {
        return "Node{" +
                "element=" + element +
                '}';
    }
}

class Test {

    public static void main(String[] args) {
        LinkStore linkStore = new LinkStore();
        linkStore.addElement(1);
        linkStore.addElement(2);
        linkStore.addElement(3);
        linkStore.addElement("t");
        System.out.println(linkStore);
        linkStore.reverseKLink(linkStore);
        System.out.println(linkStore);


    }
}